/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.service;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.I18nResource;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.entity.ResultCode;
import com.inspur.edp.web.common.entity.ResultMessage;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.utility.ListUtility;
import com.inspur.edp.web.common.utility.ResourceLocalizeUtil;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.formmetadata.constant.I18nExceptionConstant;
import com.inspur.edp.web.formmetadata.constant.I18nMsgConstant;
import com.inspur.edp.web.formmetadata.formresource.FormResourceManager;
import com.inspur.edp.web.formmetadata.i18n.constant.I18nResourceConstant;
import com.inspur.edp.web.formmetadata.replication.FormMetadataReplicator;
import com.inspur.edp.web.formmetadata.replication.ProjectInformationManager;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.i18n.framework.api.language.EcpLanguage;
import io.iec.edp.caf.i18n.framework.api.language.ILanguageService;

import javax.annotation.Resource;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * 需要通过spring 方式使用
 *
 * @author guozhiqi
 */
public class FormMetadataService {


    @Resource
    private FormResourceManager formResourceManager;

    @Resource
    private ILanguageService languageService;

    /**
     * 获取对应的bean实例
     *
     * @return
     */
    public static FormMetadataService getBeanInstance() {
        return SpringBeanUtils.getBean(FormMetadataService.class);
    }


    /**
     * 生成表单关联的中文资源元数据
     */
    public void reSaveFormIfResourceNotExists(GspMetadata formMetadata, String baseFormPath) {
        List<I18nResource> resourceList = getFormResourceWithMetaData(formMetadata, I18nResourceConstant.ZH_CHS, baseFormPath);
        if (ListUtility.isEmpty(resourceList)) {
            // 调用保存表单元数据接口，间接生成资源元数据
            MetadataService metadataService = SpringBeanUtils.getBean(MetadataService.class);
            metadataService.saveMetadata(formMetadata, Paths.get(formMetadata.getRelativePath()).resolve(formMetadata.getHeader().getFileName()).toString());
        }
    }

    /**
     * 根据表单元数据获取对应的资源列表
     *
     * @param metadata     元数据信息*
     * @param language     语言列表
     * @param baseFormPath 传递的基础表单的路径 针对组合表单，传递的也是基础表单的路径
     */
    public List<I18nResource> getFormResourceWithMetaData(GspMetadata metadata, String language, String baseFormPath) {
        return this.formResourceManager.getFormResourceWithMetaData(metadata, language, baseFormPath);
    }


    public List<EcpLanguage> getEnabledLanguageList() {
        return this.languageService.getEnabledLanguages();
    }

    public List<EcpLanguage> getBuiltinLanguageList() {
        return this.languageService.getBuiltinLanguages();
    }

    public List<EcpLanguage> getAllLanguageList() {
        return this.languageService.getAllLanguages();
    }

    public ResultMessage<String> replicateForm(String sourceMetadataId, String sourceMetadataRelativePath, String targetMetadataCode, Map<String, String> targetMetadataNameLanguage, String targetProjectName) {
        if (StringUtility.isNullOrEmpty(sourceMetadataId) || StringUtility.isNullOrEmpty(sourceMetadataRelativePath)) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0018);
        }
        if (StringUtility.isNullOrEmpty(targetMetadataCode) || targetMetadataNameLanguage == null) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0019);
        }

        //根据当前表单元数据id 获取对应的元数据信息
        // 判断当前表单元数据是否不存在
        if (!MetadataUtility.getInstance().isMetaDataExistsWithMetadataIDAndPathWithDesign(sourceMetadataRelativePath, sourceMetadataId)) {
            return ResultCode.info(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_FORM_METADATA_MSG_0009));
        }
        MetadataGetterParameter metadataGetterParameter = MetadataGetterParameter.getNewInstance(sourceMetadataId, sourceMetadataRelativePath, MetadataTypeEnum.Frm);
        metadataGetterParameter.setTargetMetadataNotFoundMessage(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_FORM_METADATA_MSG_0010));

        GspMetadata sourceFormMetadata = MetadataUtility.getInstance().getMetadataWithDesign(metadataGetterParameter);
        if (sourceFormMetadata == null) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0020, new String[]{sourceMetadataId});
        }

        // 获取待复制元数据所在工程名称
        String sourceProjectName = ProjectInformationManager.getProjectName(sourceFormMetadata);
        if (StringUtility.isNullOrEmpty(sourceProjectName)) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FORM_METADATA_ERROR_0021, new String[]{sourceMetadataId});
        }

        FormMetadataReplicator formMetadataReplicator = new FormMetadataReplicator();
        return formMetadataReplicator.replicate(sourceFormMetadata, sourceProjectName, targetMetadataCode, targetMetadataNameLanguage, targetProjectName);
    }
}
